<template>
  <Transition name="modal-fade">
    <div v-if="isVisible" class="modal-overlay" @click.self="closeModalSafely" @keydown.esc="closeModalSafely">
      <div class="modal-content"
           role="dialog"
           aria-modal="true"
           :aria-labelledby="modalTitleId"
           ref="modalContentRef"
           tabindex="-1"> 
        <button class="close-x-button" @click="closeModalSafely" :aria-label="closeButtonLabel">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="currentColor">
            <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
          </svg>
        </button>
        <h3 :id="modalTitleId" class="modal-title">会议室评价</h3>

        <div v-if="isLoading" class="status-message loading-comments">
          <p>正在加载评价...</p> {/* You can add a spinner icon here */}
        </div>
        <div v-else-if="!comments || comments.length === 0" class="status-message no-comments">
          <svg class="no-comments-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="48" height="48" fill="currentColor">
            <path d="M20 2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4V4c0-1.1-.9-2-2-2zm-2 10H6v-2h12v2zm0-3H6V7h12v2z"/>
          </svg>
          <p>暂无评价。</p>
        </div>
        <ul v-else class="comments-list">
          <li v-for="comment in comments" :key="comment.commentId" class="comment-item">
            <p class="comment-content">{{ comment.content }}</p>
            <div class="comment-meta">
              <span class="comment-time">{{ formatDateTime(comment.commentTime) }}</span>
              <span class="comment-rating">
                <template v-if="comment.rating !== undefined && comment.rating !== null">
                  <el-rate v-model="comment.rating" :max="5" disabled show-text :texts="['非常差', '差', '一般', '好', '非常好']" />
                </template>
                <template v-else>
                  暂无评分
                </template>
              </span>
            </div>
          </li>
        </ul>

        <div class="modal-actions">
          <button @click="closeModalSafely" class="close-button">{{ closeButtonLabel }}</button>
        </div>
      </div>
    </div>
  </Transition>
</template>

<script setup>
import { ref, watch, nextTick, onMounted, onUnmounted, computed } from 'vue';
import { ElRate } from 'element-plus'; // 导入 ElRate 组件

const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false
  },
  comments: {
    type: Array,
    default: () => []
  },
  isLoading: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['close']);

const modalTitleId = 'modal-title-' + Math.random().toString(36).substring(2, 9);
const modalContentRef = ref(null);
const previousActiveElement = ref(null);
const closeButtonLabel = "关闭"; // For ARIA label and button text consistency

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '日期无效';
  try {
    const date = new Date(dateTimeString);
    if (isNaN(date.getTime())) return '日期无效'; // Check for invalid date
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    });
  } catch (error) {
    console.error("Error formatting date:", error);
    return '日期格式错误';
  }
};

const closeModalSafely = () => {
  if (props.isVisible) {
    emit('close');
  }
};

const focusableElementsString = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';

const trapFocus = (event) => {
  if (event.key !== 'Tab' || !modalContentRef.value) return;

  const focusableElements = Array.from(modalContentRef.value.querySelectorAll(focusableElementsString)).filter(el => el.offsetParent !== null); // only visible, focusable elements
  if (focusableElements.length === 0) return;

  const firstElement = focusableElements[0];
  const lastElement = focusableElements[focusableElements.length - 1];

  if (event.shiftKey) { // Shift + Tab
    if (document.activeElement === firstElement) {
      lastElement.focus();
      event.preventDefault();
    }
  } else { // Tab
    if (document.activeElement === lastElement) {
      firstElement.focus();
      event.preventDefault();
    }
  }
};

watch(() => props.isVisible, async (newValue) => {
  if (newValue) {
    previousActiveElement.value = document.activeElement;
    await nextTick();
    if (modalContentRef.value) {
      modalContentRef.value.focus(); // Focus the modal content itself initially
      // Or focus the first interactive element like the close button:
      // const firstFocusable = modalContentRef.value.querySelector('.close-x-button');
      // if (firstFocusable) firstFocusable.focus();
    }
    document.addEventListener('keydown', trapFocus);
  } else {
    document.removeEventListener('keydown', trapFocus);
    if (previousActiveElement.value && typeof previousActiveElement.value.focus === 'function') {
      await nextTick(); // Ensure modal is fully gone before restoring focus
      previousActiveElement.value.focus();
    }
  }
}, { immediate: false }); // immediate:false to avoid running on initial mount if isVisible is true then

const handleEscKey = (event) => {
  if (event.key === 'Escape' && props.isVisible) {
    closeModalSafely();
  }
};

onMounted(() => {
  document.addEventListener('keydown', handleEscKey);
});

onUnmounted(() => {
  document.removeEventListener('keydown', handleEscKey);
  document.removeEventListener('keydown', trapFocus); // Ensure cleanup
});

</script>

<style scoped>
/* Define CSS variables - these are scoped to this component */
:host, .modal-overlay { /* :host is for web components, .modal-overlay makes them available within this component's scope effectively */
  --modal-padding: 2rem;
  --modal-border-radius: 8px;
  --primary-color: #007bff;
  --primary-color-hover: #0056b3;
  --text-color-dark: #333;
  --text-color-light: #666;
  --text-color-meta: #777;
  --background-color-light: #ffffff; /* Ensuring modal content is white */
  --background-color-item: #f9f9f9; /* Ensuring comment item has a light background */
  --border-color-light: #eeeeee;
  --star-color-filled: #ffc107;
  --star-color-empty: #cccccc;
  --danger-color: #dc3545; /* Example, if needed */
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.65); /* Slightly darker for better contrast */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000; /* Ensure it's on top */
}

.modal-content {
  background-color: var(--background-color-light); /* CRITICAL: This makes it not transparent */
  padding: var(--modal-padding);
  border-radius: var(--modal-border-radius);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
  width: 90%;
  max-width: 600px;
  max-height: 85vh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  position: relative;
  outline: none; /* Remove outline when modalContentRef is focused, rely on browser default for elements within */
}

/* Custom scrollbar (optional, webkit only for this example) */
.modal-content::-webkit-scrollbar {
  width: 8px;
}
.modal-content::-webkit-scrollbar-track {
  background: var(--border-color-light);
  border-radius: 4px;
}
.modal-content::-webkit-scrollbar-thumb {
  background-color: #b0b0b0;
  border-radius: 4px;
}
.modal-content::-webkit-scrollbar-thumb:hover {
  background-color: #909090;
}

.close-x-button {
  position: absolute;
  top: calc(var(--modal-padding) / 2.5);
  right: calc(var(--modal-padding) / 2.5);
  background: transparent;
  border: none;
  cursor: pointer;
  color: var(--text-color-light);
  padding: 8px; /* Increased clickable area */
  line-height: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%; /* Make it round */
  transition: background-color 0.2s ease, color 0.2s ease;
}

.close-x-button svg {
  width: 18px; /* Adjusted size */
  height: 18px;
}

.close-x-button:hover,
.close-x-button:focus-visible { /* Added focus style */
  color: var(--text-color-dark);
  background-color: rgba(0,0,0,0.05);
}

.modal-title {
  margin-top: 0;
  color: var(--text-color-dark);
  text-align: center;
  margin-bottom: 1.5rem;
  font-size: 1.6rem; /* Slightly larger title */
  font-weight: 600;
}

.status-message {
  text-align: center;
  color: var(--text-color-light);
  padding: 2rem 1rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex-grow: 1; /* Take available space */
  font-size: 1rem;
}

.no-comments-icon {
  color: #d0d0d0; /* Lighter icon color */
  margin-bottom: 0.75rem;
  width: 40px; /* Adjusted size */
  height: 40px;
}

.comments-list {
  list-style: none;
  padding: 0;
  margin: 0 0 1rem 0; /* Add some bottom margin before actions */
  flex-grow: 1;
  overflow-y: auto; /* Should not be needed if modal-content handles scroll */
}

.comment-item {
  background-color: var(--background-color-item); /* CRITICAL: This makes it not transparent */
  border: 1px solid var(--border-color-light);
  border-radius: 6px;
  padding: 1rem 1.25rem;
  margin-bottom: 1rem;
  transition: box-shadow 0.2s ease-in-out;
}
.comment-item:last-child {
  margin-bottom: 0;
}
.comment-item:hover {
  box-shadow: 0 3px 10px rgba(0,0,0,0.07);
}

.comment-content {
  margin-top: 0;
  margin-bottom: 0.85rem;
  color: var(--text-color-dark);
  line-height: 1.65;
  white-space: pre-wrap; /* Preserve line breaks in content */
  word-break: break-word; /* Prevent overflow from long words */
}

.comment-meta {
  font-size: 0.875rem;
  color: var(--text-color-meta);
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap; /* Allow meta items to wrap on small screens */
  gap: 0.5rem 1rem; /* Row and column gap */
}

.comment-time {
  /* Styles for time if needed */
}

.comment-rating {
  display: flex;
  align-items: center;
  white-space: nowrap; /* Prevent rating from wrapping */
}

.comment-rating .star {
  color: var(--star-color-empty);
  font-size: 1.1rem;
  margin-right: 2px;
  line-height: 1; /* Ensure stars align well */
}

.comment-rating .star.filled {
  color: var(--star-color-filled);
}
.comment-rating .rating-text {
  font-size: 0.8em;
  margin-left: 0.3em;
  color: var(--text-color-meta);
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 1.5rem; /* Spacing above actions */
  padding-top: 1rem;
  border-top: 1px solid var(--border-color-light);
}

.close-button {
  padding: 0.7rem 1.4rem;
  background-color: var(--primary-color);
  color: var(--background-color-light);
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 0.95rem;
  font-weight: 500;
  transition: background-color 0.2s ease, box-shadow 0.2s ease;
}

.close-button:hover,
.close-button:focus-visible { /* Added focus style */
  background-color: var(--primary-color-hover);
  box-shadow: 0 2px 8px rgba(0,123,255,0.3);
}

/* Modal Transition Animations */
.modal-fade-enter-active,
.modal-fade-leave-active {
  transition: opacity 0.25s ease;
}
.modal-fade-enter-active .modal-content,
.modal-fade-leave-active .modal-content {
  transition: transform 0.25s ease-out, opacity 0.2s ease;
}

.modal-fade-enter-from,
.modal-fade-leave-to {
  opacity: 0;
}
.modal-fade-enter-from .modal-content,
.modal-fade-leave-to .modal-content {
  transform: translateY(-25px) scale(0.97);
  opacity: 0;
}
.modal-fade-enter-to .modal-content,
.modal-fade-leave-from .modal-content {
  transform: translateY(0) scale(1);
  opacity: 1;
}
</style>